import { RESOURCE } from '../config.js'

const state = {
	resource: uni.getStorageSync(RESOURCE) || [] //资源列表
}

const getters = {
	get (state) {
		return state.resource
	}
}

const mutations = {
	set (state, resource) {
		state.resource = resource
		uni.setStorageSync(RESOURCE, state.resource)
	}
}

const actions = {
	save ({state, commit}, resource) {
		const list = [...state.resource]
		const index = list.findIndex(item => item.id == resource.id)
		index > -1 ? list[index] = Object.assign({}, list[index], resource) : list.unshift(resource)
		commit('set', list)
	},
	remove ({state, commit}, id) {
		const list = [...state.resource]
		const index = list.findIndex(item => item.id == id)
		if ( index > -1 ) list.splice(index, 1);
		commit('set', list)
	},
	clear ({state, commit}, type) {
		const list = [...state.resource]
		commit('set', type ? list.filter(item => item.type != type) : [])
	}
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
	actions
}